package com.hsgene.common.util.result;

import com.hsgene.common.util.exception.ErrorCode;

import java.io.Serializable;

/**
 * 花生仁API请求返回结果
 *
 * @author wangbing
 * @version 1.0, 2018/9/17
 */
public class PeanutApiResult<T> implements Serializable {

    private static final long serialVersionUID = 7746090991531285069L;
    /**
     * 返回结果
     */
    private T data;

    /**
     * 状态
     */
    private int status;

    /**
     * 成功与否标志（true，false）
     */
    private boolean success;

    /**
     * 时间戳
     */
    private long timestamp;

    public PeanutApiResult() {
    }

    public static <T> PeanutApiResult<T> resultValue(T data, int status, boolean success, long timestamp) {
        PeanutApiResult<T> result = new PeanutApiResult<>();
        result.setStatus(status);
        result.setSuccess(success);
        result.setTimestamp(timestamp);
        result.setData(data);
        return result;
    }

    public static <T> PeanutApiResult<T> executeFail(ErrorCode errorCode,long timestamp) {
        PeanutApiResult<T> result = new PeanutApiResult<>();
        result.setStatus(errorCode.getCode());
        result.setSuccess(false);
        result.setData((T) errorCode.getDescription());
        result.setTimestamp(timestamp);
        return result;
    }

    public static <T> PeanutApiResult<T> defaultSuccess() {
        PeanutApiResult<T> result = new PeanutApiResult<>();
        result.setStatus(200);
        result.setSuccess(true);
        result.setTimestamp(System.currentTimeMillis());
        return result;
    }

    public static <T> PeanutApiResult<T> defaultFail(ErrorCode errorCode) {
        PeanutApiResult<T> result = new PeanutApiResult<>();
        result.setStatus(errorCode.getCode());
        result.setData((T) errorCode.getDescription());
        result.setSuccess(false);
        result.setTimestamp(System.currentTimeMillis());
        return result;
    }

    public static <T> PeanutApiResult<T> from(ApiResult<T> apiResult) {
        PeanutApiResult<T> result = new PeanutApiResult<T>();
        result.setStatus(apiResult.getCode());
        result.setSuccess(apiResult.isSucc());
        result.setTimestamp(System.currentTimeMillis());
        result.setData(apiResult.getData());
        return result;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }
}
